<template>
    <div>
        <el-card class="box-card">
            <div slot="header" class="clearfix">
                <el-button size="small" type="success" @click="openAdditionDialog()">+
                    {{$t('message.term.add')}}
                </el-button>
                <el-button size="small" type="info" @click="testAdmin()">+
                    {{$t('message.term.test')}}
                </el-button>

            </div>
            <el-form style="padding: 0 10px" :inline="true" :model="formInline" class="demo-form-inline" size="small">
                <el-row :gutter="20">
                    <el-col :span="20">
                        <el-form-item :label="$t('message.term.court_name')">
                            <el-input v-model="formInline.court_name" clearable></el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :span="4">
                        <el-form-item class="fr">
                            <el-button type="primary" @click="query(1)">{{$t('message.term.search')}}</el-button>
                        </el-form-item>
                    </el-col>
                </el-row>
            </el-form>

            <PaginationTable :loading="loadingForPaginationTable" :columns="columnsDef" :data="tablePaginationData"
                             @onCurrentChange="handleCurrentPageChange"
                             @onPageSizeChange="onPageSizeChange"
                             :headerCellStyle="{background:'#f5f7fa'}">
            </PaginationTable>
        </el-card>

        <!-- 对话框 -->
        <el-dialog :title="auDialog.title" :visible.sync="auDialog.visible" :close-on-click-modal="false"
                   @close="onAUDialogClose">
            <div style="padding-right: 20px;">
                <el-form :model="formAU" ref="formAU" size="small">
                    <el-form-item :label="$t('message.term.province')"
                                  :label-width="auDialog.formLabelWidth" prop="province">
                        <el-input v-model="formAU.province" autocomplete="off"></el-input>
                    </el-form-item>

                    <el-form-item :label="$t('message.term.court_name')"
                                  :label-width="auDialog.formLabelWidth" prop="court_name">
                        <el-input v-model="formAU.court_name" autocomplete="off"></el-input>
                    </el-form-item>

                    <el-form-item :label="$t('message.term.first_instance')"
                                  :label-width="auDialog.formLabelWidth" prop="first_instance">
                        <el-select v-model="formAU.first_instance" :placeholder="$t('message.term.please_pick')">
                            <el-option
                                    v-for="item in selectOptions.first_instance"
                                    :key="item.value"
                                    :label="item.label"
                                    :value="item.value">
                            </el-option>
                        </el-select>
                    </el-form-item>

                    <el-form-item :label="$t('message.term.second_instance')"
                                  :label-width="auDialog.formLabelWidth" prop="second_instance">
                        <el-select v-model="formAU.second_instance" :placeholder="$t('message.term.please_pick')">
                            <el-option
                                    v-for="item in selectOptions.second_instance"
                                    :key="item.value"
                                    :label="item.label"
                                    :value="item.value">
                            </el-option>
                        </el-select>
                    </el-form-item>

                    <el-form-item :label="$t('message.term.address')"
                                  :label-width="auDialog.formLabelWidth" prop="address">
                        <el-input v-model="formAU.address" autocomplete="off"></el-input>
                    </el-form-item>

                    <el-form-item :label="$t('message.term.phone')"
                                  :label-width="auDialog.formLabelWidth" prop="phone">
                        <el-input v-model="formAU.phone"></el-input>
                    </el-form-item>


                    <el-form-item :label="$t('message.term.remark')"
                                  :label-width="auDialog.formLabelWidth" prop="remark">
                        <el-input type="textarea" v-model="formAU.remark"></el-input>
                    </el-form-item>

                </el-form>
            </div>
            <div slot="footer" class="dialog-footer">
                <el-button @click="closeAUDialog" size="small">{{$t('message.term.cancel')}}</el-button>
                <el-button type="primary" @click="confirmSubmitAUDialog" size="small">{{$t('message.term.confirm')}}
                </el-button>
            </div>
        </el-dialog>
    </div>
</template>
<script>
    import {API} from '@/customized/http/api';
    import Util from '@/customized/util/utils.js';
    import PaginationTable from '@/components/PaginationTable';

    export default {
        name: "CourtAddress",
        components: {
            PaginationTable
        },
        data() {
            return {
                namespace: "court_address.",
                /** 查询对应的表单 */
                formInline: {
                    court_name: '',
                    page_size: 0
                },
                /** 新增及编辑对话框对应的表单 */
                formAU: {
                    id: '',
                    version: '',
                    province: '',
                    court_name: '',
                    first_instance: '',
                    second_instance: '',
                    address: '',
                    phone: '',
                    remark: ''
                },
                /** 对话框的属性 */
                auDialog: {
                    visible: false,
                    title: "",
                    formLabelWidth: '160px'
                },
                /** 数据表是否显示正在加载中的提示 */
                loadingForPaginationTable: false,
                currentPage: 1,
                /** 数据表列的定义 */
                columnsDef: [{
                    prop: "court_name",
                    label: this.$t('message.term.court_name'),
                }, {
                    prop: "_escaped__first_instance",
                    label: this.$t('message.term.first_instance')
                }, {
                    prop: "_escaped__second_instance",
                    label: this.$t('message.term.second_instance')
                }, {
                    prop: "address",
                    label: this.$t('message.term.address')
                }, {
                    prop: "phone",
                    label: this.$t('message.term.phone')
                }, {
                    prop: "remark",
                    label: this.$t('message.term.remark')
                }, {
                    label: this.$t('message.term.action'),
                    prop: 'action',
                    fixed: "right",
                    width: 120,
                    render: (h, params) => {
                        return h('div', [
                            h('el-button', {
                                props: {
                                    type: 'text',
                                    size: 'small'
                                },
                                style: {
                                    color: '#f56c6c'
                                },
                                on: {
                                    click: () => {
                                        this.handleDeleteButton(params);
                                    }
                                }
                            }, this.$t('message.term.delete')),
                            h('el-button', {
                                props: {
                                    type: 'text',
                                    size: 'small'
                                },
                                on: {
                                    click: () => {
                                        this.handleEditButton(params);
                                    }
                                }
                            }, this.$t('message.term.edit'))
                        ]);
                    }
                }],
                /** 数据表绑定的数据集 */
                tablePaginationData: {},
                selectOptions: {
                    first_instance: [{
                        value: "y",
                        label: this.$t('message.term.y')
                    }, {
                        value: "n",
                        label: this.$t('message.term.n')
                    }],
                    second_instance: [{
                        value: "y",
                        label: this.$t('message.term.y')
                    }, {
                        value: "n",
                        label: this.$t('message.term.n')
                    }]
                },
                validatorFields: []
            }
        },
        created() {

        },
        mounted: function () {
            this.$nextTick(() => {
                this.query(this.currentPage);
            });
        },
        beforeDestroy: function () {

        },
        computed: {

        },
        methods: {
            tableHeadRender(h, data) {
                return h('span', [
                    h('el-tooltip', {attrs:{ content:data.column.label }}, [h('span', data.column.label)])
                ])
            },
            showFullScreenLoading() {
                const loading = this.$loading({
                    lock: true
                });
                return loading;
            },
            onPageSizeChange(pageSize) {
                this.formInline.page_size = pageSize;
                this.query(this.currentPage);
            },
            /**
             *  加载select的选项
             */
            loadSelectOptions() {
                let fields = [];
                for (let key in this.selectOptions) {
                    fields.push(this.namespace + key);
                }

                if (fields.length > 0) {
                    /*创建的时候开始加载校验配置*/
                    API.getSelectOptions({
                        list: JSON.stringify(fields)
                    }, '').then((response) => {
                        let optionsConfig = response.data;
                        for (let key in this.selectOptions) {
                            this.selectOptions[key] = optionsConfig[this.namespace + key];
                        }
                    }).catch((error) => {
                        console.log(error);
                    });
                }
            },
            /** 查询配置项 */
            query(page) {
                this.currentPage = page;
                let postJson = {
                    page: page,
                    ...this.formInline
                };

                this.loadingForPaginationTable = true;
                API.queryCourtAddress(postJson)
                    .then((responseData) => {
                        this.loadingForPaginationTable = false;
                        this.tablePaginationData = responseData.data;
                    })
                    .catch((exception) => {
                        this.$message.error(exception.message);
                        this.loadingForPaginationTable = false;
                    });
            },
            /** 换页 */
            handleCurrentPageChange(newPage) {
                this.query(newPage);
                this.currentPage = newPage;
            },
            /** 点击删除按钮 */
            handleDeleteButton(params) {
                let id = params.row.id;
                let version = params.row.version;
                this.$confirm(this.$t('message.term.confirm_deleting'), this.$t('message.term.tips'), {
                    confirmButtonText: this.$t('message.term.confirm'),
                    cancelButtonText: this.$t('message.term.cancel'),
                    type: 'warning'
                }).then(() => {
                    this.remove(id, version);
                }).catch((exception) => {
                    let exceptionJson = JSON.parse(exception.message);
                    this.$message.error(exceptionJson.message);
                });
            },
            /** 点击数据行的编辑按钮 */
            handleEditButton(params) {
                /** 全局加载中开启 */
                const loading = this.$loading({
                    lock: true
                });

                API.getCourtAddressDetail({id: params.row.id}).then((res) => {
                    let itemDetail = res.data;

                    /** 打开编辑对话框 */
                    this.auDialog.title = this.$t('message.term.edit') + this.$t('message.term.po_status');
                    this.auDialog.visible = true;

                    /**
                     * form表单的重置是以第一次打开的数据作为重置标准,如果先打开的是更新,那么重置之后以第一次更新的数据作为标准;
                     * Dialog 中的内容是懒加载的，目前 edit (更新)方法的写法导致 Form 刚加载出来时值就已经是新的了，
                     * 所以 resetFields 也只能回到新值
                     */
                    this.$nextTick(() => {
                        for (let attr in this.formAU) {
                            let attrValue = itemDetail[attr];
                            /** 只复制我们需要的属性 */
                            this.formAU[attr] = attrValue ? attrValue : "";
                        }
                    });

                    /** 全局加载中关闭 */
                    loading.close();
                }).catch((exception) => {
                    this.$message.error(exception.message);
                    loading.close();
                });
            },
            /** 关闭对话框 */
            closeAUDialog() {
                this.auDialog.visible = false;
            },
            /** 能同时兼顾点按钮关闭和点右上角的X关闭 */
            onAUDialogClose() {
                this.auDialog.title = "";
                this.$refs.formAU.resetFields();
            },
            /** 确定提交新增 */
            confirmSubmitAUDialog() {
                let postJson = {
                    ...this.formAU
                };

                this.$refs['formAU'].validate((valid) => {
                    if (valid) {
                        if (!Util.isBlank(this.formAU.id) && !Util.isBlank(this.formAU.version)) {
                            this.update(postJson);
                        } else {
                            this.add(postJson);
                        }
                    } else {
                        this.$message.error(this.$t('message.term.validate_fail'));
                    }
                })

                console.log(JSON.stringify(postJson));
            },
            /** 新增配置项 */
            add(postJson) {
                API.addCourtAddress(postJson)
                    .then(() => {
                        /** 提示成功 */
                        this.$message({
                            type: 'success',
                            message: this.$t('message.term.add') + " "
                                + this.$t('message.term.po_status') + " "
                                + this.$t('message.term.success')
                        });

                        this.closeAUDialog();
                        this.query(this.currentPage);
                    })
                    .catch((exception) => {
                        this.$message.error(exception.message);
                    });
            },
            /** 修改配置项 */
            update(postJson) {
                API.updateCourtAddress(postJson)
                    .then(() => {
                        /** 提示成功 */
                        this.$message({
                            type: 'success',
                            message: this.$t('message.term.edit') + " "
                                + this.$t('message.term.po_status') + " "
                                + this.$t('message.term.success')
                        });

                        this.closeAUDialog();
                        this.query(this.currentPage);
                    })
                    .catch((exception) => {
                        this.$message.error(exception.message);
                    });
            },
            /** 删除配置项 */
            remove(id, version) {
                API.removeCourtAddress({id: id, version: version})
                    .then(() => {
                        /** 提示成功 */
                        this.$message({
                            type: 'success',
                            message: this.$t('message.term.delete') + " "
                                + this.$t('message.term.po_status') + " "
                                + this.$t('message.term.success')
                        });

                        this.query(this.currentPage);
                    })
                    .catch((exception) => {
                        let exceptionJson = JSON.parse(exception.message);
                        this.$message.error(exceptionJson.message);
                    });
            },
            /** 打开新增对话框 */
            openAdditionDialog() {
                this.auDialog.title = this.$t('message.term.add') + " " + this.$t('message.term.record');
                this.auDialog.visible = true;
            },
            testAdmin() {
                API.testAdmin({})
                    .then(() => {
                        /** 提示成功 */
                        this.$message({
                            type: 'success',
                            message: this.$t('message.term.delete') + " "
                                + this.$t('message.term.po_status') + " "
                                + this.$t('message.term.success')
                        });
                    })
                    .catch((exception) => {
                        let exceptionJson = JSON.parse(exception.message);
                        this.$message.error(exceptionJson.message);
                    });
            }
        }
    }
</script>